<template>
  <div class="centermap">
    <!--    <div class="mapwrap">
          <Echart id="CenterMap" :options="options" ref="CenterMap" />
        </div>-->
    <div class="mapwrap" id="CenterMap" ref="CenterMap">
    </div>
  </div>
</template>

<script>
import xzqCode from '../../utils/map/xzqCode';
import { currentGET } from 'api/modules';
import * as echarts from 'echarts';
import { GETNOBASE, internalLeadershipCockpitQuery } from 'api';
import mapmark1 from '@/assets/img/mapmark1.png';

const zibonData = require('@/assets/370300.json');
export default {
  data() {
    return {
      chart: null,
      maptitle: '',
      options: {},
      code: 'china', //china 代表中国 其他地市是行政编码
      echartBindClick: false,
      isSouthChinaSea: false, //是否要展示南海群岛  修改此值请刷新页面
      preSelectMapIndex: 0,
      timer: null,
    };
  },
  created() {
    this.getMapData();
    this.timer = setInterval(() => {
      this.getMapData();
    }, 10000);
  },
  mounted() {
    // console.log(xzqCode);
    /*    this.$nextTick(() => {
          this.initChart();
        });*/
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    //this.chart = null
    this.intervalId = null;
    clearInterval(this.timer);
  },
  methods: {
    initChart(data) {
      const that = this;
      this.chart = echarts.init(document.getElementById('CenterMap'));
      echarts.registerMap('370300', zibonData);
      this.init('370300', data);
      this.handleMapRandomSelect();
    },
    getData(code) {
      currentGET('big8', { regionCode: code }).then((res) => {
        if (res.success) {
          this.getGeojson(res.data.regionCode, res.data.dataList);
          // this.mapclick();
        } else {
          this.$Message.warning(res.msg);
        }
      });
    },
    async getMapData() {
      const res = await internalLeadershipCockpitQuery();
      this.$nextTick(() => {
        const data = res.result.data.map(i => {
          return {
            name: i.qxmc,
            ...i,
          };
        });
        this.initChart(data);
      });
    },
    // 开启定时器
    startInterval() {
      const _self = this;
      // 应通过接口获取配置时间，暂时写死5s
      const time = 3000;
      if (this.intervalId !== null) {
        clearInterval(this.intervalId);
      }
      this.intervalId = setInterval(() => {
        _self.reSelectMapRandomArea();
      }, time);
    },
    // 重新随机选中地图区域
    reSelectMapRandomArea() {
      const length = 8;
      this.$nextTick(() => {
        try {
          const map = this.chart;
          let index = Math.floor(Math.random() * length);
          while (index === this.preSelectMapIndex || index >= length) {
            index = Math.floor(Math.random() * length);
          }
          this.preSelectMapIndex = index;
          map.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex: this.preSelectMapIndex,
          });
          map && map.dispatchAction({
            type: 'mapUnSelect',
            seriesIndex: 0,
            dataIndex: this.preSelectMapIndex,
          });

          map.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: index,
          });
          map.dispatchAction({
            type: 'mapSelect',
            seriesIndex: 0,
            dataIndex: this.preSelectMapIndex,
          });
          map && map.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: this.preSelectMapIndex,
          });
        } catch (error) {
          console.log(error);
        }
      });
    },
    handleMapRandomSelect() {
      this.$nextTick(() => {
        try {
          const map = this.chart;
          const _self = this;
          setTimeout(() => {
            _self.reSelectMapRandomArea();
          }, 0);
          // 移入区域，清除定时器、取消之前选中并选中当前
          map.on('mouseover', function(params) {
            clearInterval(_self.intervalId);
            map.dispatchAction({
              type: 'mapUnSelect',
              seriesIndex: 0,
              dataIndex: _self.preSelectMapIndex,
            });
            map.dispatchAction({
              type: 'mapSelect',
              seriesIndex: 0,
              dataIndex: params.dataIndex,
            });
            _self.preSelectMapIndex = params.dataIndex;
          });
          // 移出区域重新随机选中地图区域，并开启定时器
          map.on('globalout', () => {
            _self.reSelectMapRandomArea();
            _self.startInterval();
          });
          this.startInterval();
        } catch (error) {
          console.log(error);
        }
      });
    },
    /**
     * @description: 获取geojson
     * @param {*} name china 表示中国 其他省份行政区编码
     * @param {*} mydata 接口返回列表数据
     * @return {*}
     */
    async getGeojson(name, mydata) {
      this.code = name;
      //如果要展示南海群岛并且展示的是中国的话
      let geoname = name;
      if (this.isSouthChinaSea && name == 'china') {
        geoname = 'chinaNanhai';
      }
      //如果有注册地图的话就不用再注册 了
      let mapjson = echarts.getMap(name);
      if (mapjson) {
        mapjson = mapjson.geoJSON;
      } else {
        mapjson = await GETNOBASE(`./map-geojson/${geoname}.json`).then((res) => {
          return res;
        });
        echarts.registerMap(name, mapjson);
      }
      this.init(name, mydata, []);
    },
    init(name, data) {
      // console.log(data2);
      const bg = require('@/assets/img/mapBg.png');
      const mapmark = require('@/assets/img/mapmark.png');
      const mapmark1 = require('@/assets/img/mapmark1.png');
      const mapL = require('@/assets/img/mapL.png');
      let top = 50;
      let zoom = 1.1;
      let option = {
        backgroundColor: 'transparent',
        tooltip: {
          show: true,
          /*        formatter: function(params) {
                    if (params.data) {
                      return params.name + '：' + params.data['value'];
                    } else {
                      return params.name;
                    }
                  },*/
          formatter: function(params) {
            return `<div class="tool-map">
<div class="header"> <img class="img" src="${mapL}" alt=""><span>${params.name}</span></div>
<div class="hr"></div>
<div class="content">
<span class="text">被巡察单位：</span>
<div><span class="num">${params.data.bxcdzz}</span>个</div>
</div>
<div class="content">
<span class="text">已 经 巡 察：</span>
<div><span class="num">${params.data.yxc}</span>个</div>
</div>
<div class="content">
<span class="text" style="letter-spacing: 9px">未巡察：</span>
<div><span class="num">${params.data.wxc}</span>个</div>
</div>
</div>`;
          },
          boxShadow: ' 0 0 10px rgb(0,153,184) inset,0 0 30px rgb(0,153,184)',
          backgroundColor: ' rgba(1,17,45,0.55)',
          borderWidth: 1,
          borderRadius: 4,
          borderColor: '#327bf5',
          textStyle: {
            color: '#FFF',
          },
        },
        legend: {
          show: false,
        },
        series: [
          {
            name: '淄博',
            type: 'map',
            map: name,
            // aspectScale: 0.78,
            data: data,
            // data: [1,100],
            selectedMode: true, //是否允许选中多个区域
            zoom: zoom,
            top: top,
            label: {
              show: true,
              color: '#ffffff',
              fontSize: 18,
              fontWeight: 'bold',
              fontFamily: 'PingFangSC-Semibold',
              // position: [-10, 0],
              formatter: function(val) {
                return val.name + '\n{cIcon|}';
              },
              rich: {
                cIcon: {
                  height: 22,
                  width: 20,
                  align: 'center',
                  margin: [0, 5, 0, 5],
                  backgroundColor: {
                    image: mapmark,
                  },
                },
              },
            },
            itemStyle: {
              areaColor: {
                image: bg,
                repeat: `repeat`,
              },
              shadowOffsetX: '0', //阴影X偏移量
              shadowOffsetY: '0', //阴影Y偏移量
              shadowBlur: 30,
              shadowColor: 'rgba(14,212,255, 0.7)', // 阴影颜色
              borderColor: 'rgba(14,212,255, 1)',
              type: 'solid',
              borderWidth: 4,
              emphasis: {
                // 地图区域的高亮颜色
                areaColor: 'rgba(255,244,63,0.4)',
                color: '#fff',
                borderColor: 'rgba(255,244,63, 1)',
                borderWidth: 4,
                label: {
                  color: '#ffffff',
                  fontSize: 18,
                  fontWeight: 'bold',
                  fontFamily: 'PingFangSC-Semibold',
                  rich: {
                    cIcon: {
                      backgroundColor: {
                        image: mapmark1,
                      },
                    },
                  },
                },
              },
            },

          },
        ],
        //动画效果
        animationDuration: 1000,
        animationEasing: 'linear',
        animationDurationUpdate: 1000,
      };
      this.options = option;
      this.chart.setOption(option);
    },
    message(text) {
      this.$Message({
        text: text,
        type: 'warning',
      });
    },
    mapclick() {
      if (this.echartBindClick) return;
      //单击切换到级地图，当mapCode有值,说明可以切换到下级地图
      this.$refs.CenterMap.chart.on('click', (params) => {
        // console.log(params);
        let xzqData = xzqCode[params.name];
        if (xzqData) {
          this.getData(xzqData.adcode);
        } else {
          this.message('暂无下级地市!');
        }
      });
      this.echartBindClick = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(
          92deg,
          #0072ff 0%,
          #00eaff 48.8525390625%,
          #01aaff 100%
      );
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("../../assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("../../assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 930px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5),
      0 0 6px rgba(0, 237, 237, 0.4);
    }
  }
}
</style>
